#include "WindowList.h"

WindowList windowList[WINDOW_NUM];
WindowList *pWindowHead;
WindowList *pWindowTail;

WindowList* WindowMalloc(void);

void initWindowList(void)
{
  pWindowHead = 0;
  pWindowTail = 0;
  for(int i = 0; i < WINDOW_NUM; i++)
  {
    windowList[i].pWindow = NULL;
    windowList[i].pNext = NULL;
    windowList[i].pPrev = NULL;
  }
  return;
}

WindowList* WindowMalloc(void)
{
  for(int i = 0; i < WINDOW_NUM; i++)
  {
    if(windowList[i].pNext == 0 && windowList[i].pWindow == 0 && windowList[i].pPrev == 0)  
    {
      return &windowList[i];
    }
  }
  return 0; 
}

uint8_t addWindowToHead(Window *p)
{
  WindowList* q = WindowMalloc();
  if(!q){
    return 0;
  }
  
  q->pWindow = p;
  if(pWindowHead)
  {
    q->pNext = pWindowHead;
    pWindowHead->pPrev = q;
    pWindowHead = q;
    q->pPrev = NULL;
  }
  else
  {
    pWindowHead = q;
    q->pNext = NULL;
    q->pPrev = NULL;
    pWindowTail = q;
  }
  return 1;
}

uint8_t carryToHead(Window *p)
{
  WindowList* q = FindWindow(p);
  if(!q){
    return 0;
  }
  
  if(!q->pPrev)
    return 1;
  
  if(q->pNext && q->pPrev)//no head no tail
  {
    q->pNext->pPrev = q->pPrev;
    q->pPrev->pNext = q->pNext;
  }
  
  if(!q->pNext && q->pPrev)//Tail
  {
    q->pPrev->pNext = NULL;
    pWindowTail = q->pPrev;
  }
  
  pWindowHead->pPrev = q;
  q->pNext = pWindowHead;

  q->pPrev = NULL;
  pWindowHead = q;
  return 1;
}


uint8_t carryToBottom(Window *p)
{
  WindowList* q = FindWindow(p);
  if(!q){
    return 0;
  }
  
  if(q->pNext && !q->pPrev) 
  {
    q->pNext->pPrev = NULL;
    pWindowHead = q->pNext;
  } 
  
  if(q->pNext && q->pPrev)
  {
    q->pNext->pPrev = q->pPrev;
    q->pPrev->pNext = q->pNext;
  }
  
  q->pPrev = pWindowTail;
  pWindowTail->pNext = q;

  q->pNext = NULL;
  pWindowTail = q;
  return 1;
}

uint8_t isWindowHead(Window *p)
{
  if(pWindowHead->pWindow == p)
  {
    return 1;
  }
  return 0;
}

uint8_t isWindowTail(Window *p)
{
  if(pWindowTail->pWindow == p)
  {
    return 1;
  }
  return 0;
}

WindowList* FindWindow(Window *p)
{
  WindowList* q = pWindowHead;
  while(q)
  {
    if(q->pWindow == p)
      return q;
    q = q->pNext;
  }
  return NULL;
}

uint8_t getWindowNum()
{
  uint8_t num = 0;
  WindowList* p = pWindowHead;
  while(p)
  {
    num++;
    p = p->pNext;
  }
  return num;
}

Window* getWindowHead(void)
{
  return pWindowHead->pWindow;
}

Window* getWindowTail(void)
{
  return pWindowTail->pWindow;
}

